import MQTT from 'mqtt'
import config from '../../config.json' assert { type: 'json' }
import logger from '../utils/logger.js'
import { findHandler } from './handler.js'
import { MQTT_TOPIC } from '../../constant.js'
import { v4 } from 'uuid'

const { brokerPath, port } = config.mqtt
const brokerURL = `${brokerPath}:${port}`

// 连接 broker
const mqttClient = MQTT.connect(brokerURL, { clientId: v4() })

// --------------- 事件监听
mqttClient.on('error', (error) => {
    logger.error(`[MQTT] error: `, error)
    mqttClient.end()
})

mqttClient.on('disconnect', () => { logger.info('[MQTT disconnect') })

mqttClient.on('connect', () => {
    logger.info(`[MQTT] connect to ${brokerURL}`)
    // 订阅某些 topic 的信息
    mqttClient.subscribe(MQTT_TOPIC.USER_REGISTER, {
        qos: 2,
        retain: false
    })
})

// 接收 topic 推送
mqttClient.on('message', (topic, payload) => {
    const payloadText = payload.toString()
    logger.info(`[MQTT] message topic: ${topic}; payload: ${payloadText}`)
    const handler = findHandler(topic)
    handler?.(mqttClient, JSON.parse(payloadText))
})

export default mqttClient
